<template>
    <ElDialog
      v-model="visible"
      :title="type === 'add' ? '添加用户' : '编辑用户'"
      width="30%"
      align-center
    >
      <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <ElFormItem label="类型名称" prop="sourceName">
          <ElInput v-model="formData.sourceName" />
        </ElFormItem>
        <ElFormItem label="类型编码" prop="sourceCode">
          <ElInput v-model="formData.sourceCode" />
        </ElFormItem>
        <ElFormItem label="状态" prop="status">
          <ElSelect v-model="formData.status">
            <ElOption label="启用" value=1 />
            <ElOption label="停用" value=0 />
          </ElSelect>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="handleCancel">取消</ElButton>
          <ElButton type="primary" @click="handleSubmit">提交</ElButton>
        </div>
      </template>
    </ElDialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { CustomerFollowTaskApi } from '@/api/customer/followTask'
  import { ApiStatus } from '@/utils/http/status'
  import { CustomerSourceFormData } from '../types'
  
  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true
    },
    type: {
      type: String,
      default: 'add'
    },
    roleList: {
      type: Array,
      default: () => []
    },
    initialFormData: {
      type: Object,
      default: () => ({})
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])
  
  const visible = ref(props.modelValue)
  const formRef = ref<FormInstance>()
  
  const formData = reactive<CustomerSourceFormData>({
    sourceName: '',
    sourceCode: ''
  })
  
  // 监听 modelValue 的变化
  watch(() => props.modelValue, (newVal) => {
    visible.value = newVal
  })
  
  // 监听 visible 的变化
  watch(visible, (newVal) => {
    emit('update:modelValue', newVal)
  })
  
  // 监听 initialFormData 的变化
  watch(() => props.initialFormData, (newVal) => {
    Object.assign(formData, newVal)
  }, { deep: true })
  
  const rules: FormRules = {
    sourceName: [
      { required: true, message: '请输入', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    sourceCode: [
      { required: true, message: '请输入', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择', trigger: 'blur' },
    ]
  }
  
  const handleSubmit = async () => {
    if (!formRef.value) return
  
    await formRef.value.validate(async (valid) => {
      if (valid) {
        console.log('验证通过---',formData)
        try{
          console.log('props.initialFormDat---',props.initialFormData)
          console.log('props.type---',props.type)
          let params = {...formData}
          if (props.type === 'add') {
            const res = await CustomerFollowTaskApi.createCustomerSource(params)
            if (res.code === ApiStatus.success) {
              ElMessage.success('添加成功')
            }
          } else {
            params.id = formData.id
            const res = await CustomerFollowTaskApi.updateCustomerSource(params)
            if (res.code === ApiStatus.success) {
              ElMessage.success('更新成功')
            }
          }
          console.log('执行到这')
          emit('submit', { ...formData })
        }catch(err){
          console.error('操作失败:', err)
          ElMessage.error('操作失败，请重试')
        }
        // visible.value = false
      }
    })
  }
  
  const handleCancel = () => {
    emit('cancel')
    // visible.value = false
  }
  </script>
  